package com.csit.service.impl;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.csit.bean.Pager;
import com.csit.dao.SaleDetailDao;
import com.csit.entity.Product;
import com.csit.entity.Sale;
import com.csit.entity.SaleDetail;
import com.csit.service.SaleDetailService;
import com.csit.util.ListAndJsonUtil;
import com.csit.util.StringUtil;

@Service
public class SaleDetailServiceImpl extends BaseServiceImpl<SaleDetail, Integer> implements SaleDetailService {
	
	@Resource
	private SaleDetailDao saleDetailDao;
	
	@Resource
	public void setBaseDao(SaleDetailDao saleDetailDao) {
		super.setBaseDao(saleDetailDao);
	}
	
	public String querySaleDetail(Integer pageNumber, Integer pageSize,Sale sale, Date beginDate, Date endDate) {
		Pager pager = new Pager(pageNumber, pageSize);
		pager = saleDetailDao.querySaleDetail(pager, sale, beginDate, endDate);
		String[] propertiesName = {"sale.saleID","sale.saleCode","sale.customerName","sale.saleer","sale.saleDate","sale.storeHouseName",
								   "sale.cash","sale.card","sale.member",
						           "quantity","price","amount","product.productName","product.productSize","product.unitName"};
		String jsonArray = ListAndJsonUtil.getJSONString(pager.getList(), propertiesName, pager.getTotalCount());
		return jsonArray;
	}

	public String querySaleDetail(Integer pageNumber, Integer pageSize,Sale sale, String productids, Date beginDate, Date endDate) {
		Pager pager = new Pager(pageNumber, pageSize);
		SaleDetail saleDetail = new SaleDetail();
		if(StringUtil.isNotNull(productids)){
			Product product = new Product();
			product.setProductID(Integer.parseInt(productids));
			saleDetail.setProduct(product);
		}
		pager = saleDetailDao.querySaleDetail(pager, sale, saleDetail, beginDate, endDate);
		
		String[] propertiesName = {"sale.saleID","sale.saleCode","sale.customerName","sale.saleer","sale.saleDate","sale.storeHouseName",
				   "sale.cash","sale.card","sale.member",
		           "quantity","price","amount","product.productName","product.productSize","product.unitName"};
		
		Map<String, Double> map = saleDetailDao.queryTotal(sale, saleDetail, beginDate, endDate);
		Double totalQty = map.get("totalQty");
		Double totalAmount = map.get("totalAmount");
		
		String jsonArray = ListAndJsonUtil.getJSONString(pager.getList(), propertiesName, pager.getTotalCount());
		
		StringBuilder json = new StringBuilder(jsonArray.substring(0, jsonArray.length()-1));
		json.append(",\"footer\":[{\"unitName\":\"统计\",\"quantity\":").append(totalQty).append(",\"amount\":").append(totalAmount).append("}]}");
		return json.toString();
	}

	public Map<String, Double> countSaleDetail(Sale sale, Date beginDate,Date endDate) {
		SaleDetail saleDetail = new SaleDetail();
		return saleDetailDao.queryTotal(sale, saleDetail, beginDate, endDate);
	}
}
